import api from '@/utils/api'

const state = {
  userInfo: null,
  token: uni.getStorageSync('token') || '',
  isLogin: false,
  userType: 1 // 1: 求职者, 2: 招聘者
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    uni.setStorageSync('token', token)
  },
  
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    state.isLogin = true
    uni.setStorageSync('userInfo', userInfo)
  },
  
  SET_USER_TYPE(state, userType) {
    state.userType = userType
    uni.setStorageSync('userType', userType)
  },
  
  LOGOUT(state) {
    state.token = ''
    state.userInfo = null
    state.isLogin = false
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('userType')
  }
}

const actions = {
  // 登录
  async login({ commit }, loginForm) {
    try {
      const response = await api.post('/auth/login', loginForm)
      const { token, user } = response.data
      
      commit('SET_TOKEN', token)
      commit('SET_USER_INFO', user)
      
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 注册
  async register({ commit }, registerForm) {
    try {
      const response = await api.post('/auth/register', registerForm)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 获取用户信息
  async getUserInfo({ commit, state }) {
    try {
      const response = await api.get('/user/profile')
      commit('SET_USER_INFO', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 更新用户信息
  async updateUserInfo({ commit }, userInfo) {
    try {
      const response = await api.put('/user/profile', userInfo)
      commit('SET_USER_INFO', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 验证token
  async validateToken({ commit }, token) {
    try {
      const response = await api.get('/auth/validate', {
        headers: { Authorization: `Bearer ${token}` }
      })
      commit('SET_USER_INFO', response.data)
      return response
    } catch (error) {
      commit('LOGOUT')
      throw error
    }
  },
  
  // 退出登录
  logout({ commit }) {
    commit('LOGOUT')
    // 跳转到登录页
    uni.reLaunch({
      url: '/pages/auth/login'
    })
  }
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  isLogin: state => state.isLogin,
  userType: state => state.userType,
  userId: state => state.userInfo ? state.userInfo.id : null,
  userName: state => state.userInfo ? state.userInfo.name : '',
  userAvatar: state => state.userInfo ? state.userInfo.avatar : ''
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}